<template>
  <div class="interaction-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日浏览数</span>
              <el-tag size="small" type="success">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ todayLikes }}</div>
            <div class="trend" :class="{ 'up': likesTrend > 0, 'down': likesTrend < 0 }">
              {{ Math.abs(likesTrend) }}% {{ likesTrend > 0 ? '↑' : '↓' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>今日收藏数</span>
              <el-tag size="small" type="warning">实时</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ todayFavorites }}</div>
            <div class="trend" :class="{ 'up': favoritesTrend > 0, 'down': favoritesTrend < 0 }">
              {{ Math.abs(favoritesTrend) }}% {{ favoritesTrend > 0 ? '↑' : '↓' }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总互动数</span>
              <el-tag size="small" type="info">总计</el-tag>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ totalInteractions }}</div>
            <div class="trend" :class="{ 'up': interactionsTrend > 0, 'down': interactionsTrend < 0 }">
              {{ Math.abs(interactionsTrend) }}% {{ interactionsTrend > 0 ? '↑' : '↓' }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 标签页切换不同类型的互动 -->
    <el-card class="interaction-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="浏览管理" name="likes">
          <div class="tab-content">
            <!-- 搜索栏 -->
            <div class="search-bar">
              <el-input
                v-model="searchQuery"
                placeholder="搜索用户昵称/商品名称"
                clearable
                @clear="handleSearch"
                @input="handleSearch"
                style="width: 300px"
              >
                <template #prefix>
                  <i class="el-icon-search"></i>
                </template>
              </el-input>
              <el-select
                v-model="productFilter"
                placeholder="商品分类"
                clearable
                @change="handleSearch"
                style="width: 150px; margin-left: 10px"
              >
                <el-option
                  v-for="item in categories"
                  :key="item.categoryId"
                  :label="item.name"
                  :value="item.categoryId"
                />
              </el-select>
            </div>

            <!-- 点赞列表 -->
            <el-table
              v-loading="loading"
              :data="paginatedList"
              border
              style="width: 100%"
              row-key="interactionId"
            >
              <el-table-column prop="interactionId" label="ID" width="220"></el-table-column>
              <el-table-column label="用户" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.userNickname }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品" width="200">
                <template slot-scope="scope">
                  <span>{{ scope.row.productTitle }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品分类" width="120">
                <template slot-scope="scope">
                  {{ getCategoryNameByProductId(scope.row.productId) }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" :label="activeTab === 'likes' ? '浏览时间' : '收藏时间'" width="180">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row, activeTab === 'likes' ? 'view' : 'favorite')"
                    plain
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="收藏管理" name="favorites">
          <div class="tab-content">
            <!-- 搜索栏 -->
            <div class="search-bar">
              <el-input
                v-model="searchQuery"
                placeholder="搜索用户昵称/商品名称"
                clearable
                @clear="handleSearch"
                @input="handleSearch"
                style="width: 300px"
              >
                <template #prefix>
                  <i class="el-icon-search"></i>
                </template>
              </el-input>
              <el-select
                v-model="productFilter"
                placeholder="商品分类"
                clearable
                @change="handleSearch"
                style="width: 150px; margin-left: 10px"
              >
                <el-option
                  v-for="item in categories"
                  :key="item.categoryId"
                  :label="item.name"
                  :value="item.categoryId"
                />
              </el-select>
            </div>

            <!-- 收藏列表 -->
            <el-table
              v-loading="loading"
              :data="paginatedList"
              border
              style="width: 100%"
              row-key="interactionId"
            >
              <el-table-column prop="interactionId" label="ID" width="220"></el-table-column>
              <el-table-column label="用户" width="120">
                <template slot-scope="scope">
                  <span>{{ scope.row.userNickname }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品" width="200">
                <template slot-scope="scope">
                  <span>{{ scope.row.productTitle }}</span>
                </template>
              </el-table-column>
              <el-table-column label="商品分类" width="120">
                <template slot-scope="scope">
                  {{ getCategoryNameByProductId(scope.row.productId) }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" :label="activeTab === 'likes' ? '浏览时间' : '收藏时间'" width="180">
                <template slot-scope="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row, activeTab === 'likes' ? 'view' : 'favorite')"
                    plain
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size.sync="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="dynamicTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-ui'
import interactionService from '@/services/interaction.service'
import userService from '@/services/user.service'
import productService from '@/services/product.service'
import categoryService from '@/services/category.service'

export default {
  name: 'InteractionList',
  data() {
    return {
      // 状态定义
      interactions: [],
      users: [],
      products: [],
      loading: false,
      searchQuery: '',
      productFilter: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      activeTab: 'likes',
      // 统计数据
      todayLikes: 0,
      likesTrend: 0,
      todayFavorites: 0,
      favoritesTrend: 0,
      totalInteractions: 0,
      interactionsTrend: 0,
      // 列表数据
      categories: []
    }
  },
  computed: {
    // 过滤后的列表
    filteredLikes() {
      // 根据后端模型，type=1是收藏，type=2是浏览，这里暂时将浏览当作点赞显示
      console.log('=== 浏览记录过滤调试 ===')
      console.log('所有互动记录:', this.interactions)
      console.log('type字段分布:', this.interactions.map(item => ({ 
        id: item.interactionId, 
        type: item.type, 
        typeType: typeof item.type,
        userNickname: item.userNickname,
        productTitle: item.productTitle
      })))
      
      // 尝试多种过滤条件
      const result1 = this.interactions.filter(item => item.type === 2)
      const result2 = this.interactions.filter(item => item.type === '2')
      const result3 = this.interactions.filter(item => item.type == 2)
      const result4 = this.interactions.filter(item => item.type !== 1) // 显示非收藏的记录
      
      console.log('过滤结果 - type === 2:', result1)
      console.log('过滤结果 - type === "2":', result2)
      console.log('过滤结果 - type == 2:', result3)
      console.log('过滤结果 - type !== 1:', result4)
      
      // 暂时显示所有非收藏的记录
      let result = result4
      
      // 根据分类过滤
      if (this.productFilter) {
        result = result.filter(item => {
          const product = this.products.find(p => p.productId === item.productId)
          return product && product.categoryId === this.productFilter
        })
      }
      
      // 根据搜索关键词过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item => 
          (item.userNickname && item.userNickname.toLowerCase().includes(query)) ||
          (item.productTitle && item.productTitle.toLowerCase().includes(query))
        )
      }
      
      return result
    },
    filteredFavorites() {
      // 根据后端模型，type=1是收藏
      let result = this.interactions.filter(item => item.type === 1)
      console.log('收藏记录过滤结果:', result)
      
      // 根据分类过滤
      if (this.productFilter) {
        result = result.filter(item => {
          const product = this.products.find(p => p.productId === item.productId)
          return product && product.categoryId === this.productFilter
        })
      }
      
      // 根据搜索关键词过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(item => 
          (item.userNickname && item.userNickname.toLowerCase().includes(query)) ||
          (item.productTitle && item.productTitle.toLowerCase().includes(query))
        )
      }
      
      return result
    },
    
    // 当前显示的列表
    currentList() {
      return this.activeTab === 'likes' ? this.filteredLikes : this.filteredFavorites
    },
    
    // 分页后的列表
    paginatedList() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.currentList.slice(start, end)
    },
    
    // 动态计算总数
    dynamicTotal() {
      return this.currentList.length
    }
  },
  watch: {
    // 监听路由变化
    '$route.path'(newPath) {
      if (newPath === '/interaction/list') {
        const token = localStorage.getItem('token')
        if (token) {
          this.initializeData()
        }
      }
    }
  },
  mounted() {
    // 组件挂载时获取数据
    const token = localStorage.getItem('token')
    if (token) {
      this.initializeData()
    }
  },
  methods: {
    // 初始化数据
    async initializeData() {
      try {
        // 并行加载基础数据
        await Promise.all([
          this.fetchStatistics(),
          this.fetchUsers(),
          this.fetchProducts(),
          this.fetchCategories()
        ])
        
        // 基础数据加载完成后，再加载互动数据
        await this.fetchInteractions()
      } catch (error) {
        console.error('初始化数据失败:', error)
      }
    },
    // 获取互动列表
    async fetchInteractions() {
      try {
        this.loading = true
        
        const response = await interactionService.getList({
          page: this.currentPage,
          pageSize: this.pageSize,
          type: this.activeTab,
          search: this.searchQuery,
          productId: this.productFilter
        })
        
        console.log('互动列表API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的互动数组数据:', data)
            } else if (Array.isArray(data)) {
              // 数据本身就是数组
              console.log('数据本身就是数组格式:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'interactions', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到互动数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到互动数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象，设置为空数组
            data = []
          }
          
          // 处理数据，添加显示字段
          this.interactions = (data || []).map(item => {
            console.log('处理单个互动记录:', item)
            const userNickname = this.getUserNickname(item.userId)
            const productTitle = this.getProductTitle(item.productId)
            
            console.log('用户ID:', item.userId, '用户昵称:', userNickname)
            console.log('商品ID:', item.productId, '商品标题:', productTitle)
            
            return {
              ...item,
              userNickname: userNickname,
              productTitle: productTitle,
              // 保持原始的type字段，不进行转换
              type: item.type
            }
          })
          
          this.total = this.interactions.length
          console.log('处理后的互动列表:', this.interactions)
          console.log('互动列表长度:', this.interactions.length)
          console.log('原始数据示例:', data[0])
          console.log('处理后数据示例:', this.interactions[0])
        } else {
          console.error('API返回错误:', response)
          this.interactions = []
          this.total = 0
          ElMessage.error(response?.message || '获取互动列表失败')
        }
      } catch (error) {
        console.error('获取互动列表失败:', error)
        // 修复错误处理，避免访问 undefined 的 error 属性
        const errorMessage = error?.response?.data?.message || error?.message || '获取互动列表失败'
        ElMessage.error(errorMessage)
        this.interactions = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 获取统计数据
    async fetchStatistics() {
      try {
        const response = await interactionService.getStatistics()
        console.log('统计数据API响应:', response)
        
        if (response && response.code === 200) {
          // 处理Entity Framework格式的数据
          let data = response.data
          if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values[0] || {}
              console.log('找到Entity Framework格式的统计数据:', data)
            } else if (Array.isArray(data)) {
              data = data[0] || {}
              console.log('数据本身就是数组格式:', data)
            } else {
              // 数据本身就是对象
              console.log('数据本身就是对象格式:', data)
            }
          } else {
            data = {}
          }
          
          this.todayLikes = data.todayLikes || 0
          this.likesTrend = data.likesTrend || 0
          this.todayFavorites = data.todayFavorites || 0
          this.favoritesTrend = data.favoritesTrend || 0
          this.totalInteractions = data.totalInteractions || 0
          this.interactionsTrend = data.interactionsTrend || 0
          
          console.log('统计数据:', {
            todayLikes: this.todayLikes,
            likesTrend: this.likesTrend,
            todayFavorites: this.todayFavorites,
            favoritesTrend: this.favoritesTrend,
            totalInteractions: this.totalInteractions,
            interactionsTrend: this.interactionsTrend
          })
        } else {
          console.error('API返回错误:', response)
          // 设置默认值
          this.todayLikes = 0
          this.likesTrend = 0
          this.todayFavorites = 0
          this.favoritesTrend = 0
          this.totalInteractions = 0
          this.interactionsTrend = 0
          ElMessage.error(response?.message || '获取统计数据失败')
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
        // 修复错误处理，避免访问 undefined 的 error 属性
        const errorMessage = error?.response?.data?.message || error?.message || '获取统计数据失败'
        ElMessage.error(errorMessage)
        // 设置默认值
        this.todayLikes = 0
        this.likesTrend = 0
        this.todayFavorites = 0
        this.favoritesTrend = 0
        this.totalInteractions = 0
        this.interactionsTrend = 0
      }
    },

    // 标签页切换
    handleTabClick() {
      // 标签页切换逻辑已通过计算属性实现，无需调用API
      console.log('切换到标签页:', this.activeTab)
    },

    // 搜索
    handleSearch() {
      // 搜索逻辑已通过计算属性实现，无需调用API
      console.log('搜索条件:', {
        searchQuery: this.searchQuery,
        productFilter: this.productFilter
      })
    },

    // 删除互动
    async handleDelete(row, type) {
      try {
        await ElMessageBox.confirm(
          `确定要删除这条${type === 'view' ? '浏览' : '收藏'}记录吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await interactionService.deleteInteraction(row.interactionId)
        ElMessage.success('删除成功')
        await this.fetchInteractions()
        await this.fetchStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除互动记录失败:', error)
          // 修复错误处理，避免访问 undefined 的 error 属性
          const errorMessage = error?.response?.data?.message || error?.message || '删除失败'
          ElMessage.error(errorMessage)
        }
      }
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 重置到第一页
    },

    handleCurrentChange(val) {
      this.currentPage = val
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return d.toLocaleString()
    },

    // 获取用户列表
    async fetchUsers() {
      try {
        const response = await userService.getUsers()
        console.log('用户API响应:', response)
        
        if (response && response.code === 200) {
          // 处理后端返回的数据
          let data = response.data
          if (data && Array.isArray(data)) {
            // 数据本身就是数组
            console.log('数据本身就是数组格式:', data)
          } else if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的用户数组数据:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'users', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到用户数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到用户数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象或数组，设置为空数组
            data = []
          }
          
          this.users = data || []
          console.log('用户列表:', this.users)
          console.log('用户列表长度:', this.users.length)
        } else {
          console.error('API返回错误:', response)
          this.users = []
          ElMessage.error(response?.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        console.error('错误详情:', {
          message: error?.message,
          response: error?.response,
          status: error?.response?.status,
          data: error?.response?.data
        })
        
        // 安全的错误消息处理
        let errorMessage = '获取用户列表失败'
        if (error?.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error?.message) {
          errorMessage = error.message
        }
        
        ElMessage.error(errorMessage)
        this.users = []
      }
    },

    // 获取商品列表
    async fetchProducts() {
      try {
        const response = await productService.getProducts()
        console.log('商品API响应:', response)
        
        if (response && response.code === 200) {
          // 处理后端返回的数据
          let data = response.data
          if (data && Array.isArray(data)) {
            // 数据本身就是数组
            console.log('数据本身就是数组格式:', data)
          } else if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的商品数组数据:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'products', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到商品数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到商品数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象或数组，设置为空数组
            data = []
          }
          
          this.products = data || []
          console.log('商品列表:', this.products)
          console.log('商品列表长度:', this.products.length)
        } else {
          console.error('API返回错误:', response)
          this.products = []
          ElMessage.error(response?.message || '获取商品列表失败')
        }
      } catch (error) {
        console.error('获取商品列表失败:', error)
        console.error('错误详情:', {
          message: error?.message,
          response: error?.response,
          status: error?.response?.status,
          data: error?.response?.data
        })
        
        // 安全的错误消息处理
        let errorMessage = '获取商品列表失败'
        if (error?.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error?.message) {
          errorMessage = error.message
        }
        
        ElMessage.error(errorMessage)
        this.products = []
      }
    },

    // 获取用户昵称
    getUserNickname(userId) {
      console.log('获取用户昵称 - 用户ID:', userId, '用户列表长度:', this.users.length)
      
      if (!userId) {
        console.log('用户ID为空，返回未知用户')
        return '未知用户'
      }
      
      if (!this.users.length) {
        console.log('用户列表为空，返回未知用户')
        return '未知用户'
      }
      
      // 尝试多种字段匹配
      const user = this.users.find(u => 
        u.userId === userId || 
        u.id === userId || 
        u.UserId === userId ||
        String(u.userId) === String(userId) ||
        String(u.id) === String(userId) ||
        String(u.UserId) === String(userId)
      )
      
      if (user) {
        const nickname = user.nickname || user.Nickname || user.name || user.Name || '未知昵称'
        console.log('找到用户:', user, '昵称:', nickname)
        return nickname
      } else {
        console.log('未找到用户，用户ID:', userId)
        console.log('用户列表示例:', this.users.slice(0, 3))
        return '未知用户'
      }
    },

    // 获取商品标题
    getProductTitle(productId) {
      console.log('获取商品标题 - 商品ID:', productId, '商品列表长度:', this.products.length)
      
      if (!productId) {
        console.log('商品ID为空，返回未知商品')
        return '未知商品'
      }
      
      if (!this.products.length) {
        console.log('商品列表为空，返回未知商品')
        return '未知商品'
      }
      
      // 尝试多种字段匹配
      const product = this.products.find(p => 
        p.productId === productId || 
        p.id === productId || 
        p.ProductId === productId ||
        String(p.productId) === String(productId) ||
        String(p.id) === String(productId) ||
        String(p.ProductId) === String(productId)
      )
      
      if (product) {
        const title = product.title || product.Title || product.name || product.Name || '未知商品'
        console.log('找到商品:', product, '标题:', title)
        return title
      } else {
        console.log('未找到商品，商品ID:', productId)
        console.log('商品列表示例:', this.products.slice(0, 3))
        return '未知商品'
      }
    },

    // 获取分类数据
    async fetchCategories() {
      try {
        const response = await categoryService.getCategories()
        console.log('分类API响应:', response)
        
        if (response && response.code === 200) {
          // 处理后端返回的数据
          let data = response.data
          if (data && Array.isArray(data)) {
            // 数据本身就是数组
            console.log('数据本身就是数组格式:', data)
          } else if (data && typeof data === 'object') {
            // 检查Entity Framework的$values属性
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
              console.log('找到Entity Framework格式的分类数组数据:', data)
            } else {
              // 尝试从其他可能的属性中获取数组
              const possibleArrayKeys = ['items', 'list', 'categories', 'data', 'result']
              for (const key of possibleArrayKeys) {
                if (Array.isArray(data[key])) {
                  data = data[key]
                  console.log(`找到分类数组数据在属性 ${key}:`, data)
                  break
                }
              }
              // 如果还是找不到数组，设置为空数组
              if (!Array.isArray(data)) {
                console.warn('无法找到分类数组数据，设置为空数组')
                data = []
              }
            }
          } else {
            // 如果data不是对象或数组，设置为空数组
            data = []
          }
          
          this.categories = data || []
          console.log('分类列表:', this.categories)
          console.log('分类列表长度:', this.categories.length)
        } else {
          console.error('API返回错误:', response)
          this.categories = []
          ElMessage.error(response?.message || '获取分类列表失败')
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        console.error('错误详情:', {
          message: error?.message,
          response: error?.response,
          status: error?.response?.status,
          data: error?.response?.data
        })
        
        // 安全的错误消息处理
        let errorMessage = '获取分类列表失败'
        if (error?.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error?.message) {
          errorMessage = error.message
        }
        
        ElMessage.error(errorMessage)
        this.categories = []
      }
    },

    // 获取分类名称
    getCategoryNameByProductId(productId) {
      const product = this.products.find(p => p.productId === productId)
      if (!product) return '未知分类';
      const category = this.categories.find(c => c.categoryId === product.categoryId)
      return category ? category.name : '未知分类';
    }
  }
}
</script>

<style scoped>
.interaction-container {
  padding: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.trend {
  font-size: 14px;
  &.up {
    color: #67C23A;
  }
  &.down {
    color: #F56C6C;
  }
}

.interaction-card {
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.tab-content {
  margin-top: 20px;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 